<?php

define('DATABASE_DRIVER', 'mysql');
define('DATABASE_HOST', 'localhost');
define('DATABASE_LOGIN', 'root');
define('DATABASE_PASSWORD','');
define('DATABASE_NAME','japword');
define('CLASS_PATH', '../common/classes/');

require_once('txt_excel.helper.php');
require_once("../libs/ValhallaKeys/SimpleORM/SimpleORM.php");
require_once(CLASS_PATH."term.class.php");
require_once(CLASS_PATH."translation.class.php");


$CSV = "voc2.txt";

/*
$DBNAME = "japword";
$HOST = "localhost";
$USERNAME = "root";
$PASSWORD = "";
$db = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USERNAME, $PASSWORD, array( PDO::ATTR_PERSISTENT => false));
$st = $db->prepare('SELECT terms.*, translations.* FROM terms JOIN translations ON translations.id_term = terms.id_term');
$st->execute();
foreach(range(0, $st->columnCount() - 1) as $column_index) {
	$meta[] = $st->getColumnMeta($column_index);
}
print_r($meta);
exit();

while ($row = $st->fetch()) {
	print_r($row);
}
exit();
*/

$f = fopen($CSV,'r');
$lastword = "";

$json = array();
$lastjsonentry = array();

while ($row = TxtExcelHelper::getNextRow($f)) {
	
	$word = $row[0];
	$translation = $row[1];
	$newtranslation = true;
	
	if ($row[0] == "") {
		$newtranslation = false;
	}
	
	if ($newtranslation) {
		if (!empty($lastjsonentry)) {
			$json[] = $lastjsonentry;
		}
		$lastjsonentry = array(
			'word' => $word,
			'translation' => $translation
		);
	} else {
		if (!is_array($lastjsonentry['translation'])) {
			$lastjsonentry['translation'] = array($lastjsonentry['translation']);
		}
		
		$lastjsonentry['translation'][] = $translation;
	}
	
	$subtranslation = null;
}

$db = new Database();
$db->query('TRUNCATE TABLE terms');
$db->query('TRUNCATE TABLE translations');

foreach ($json as $data) {
	$kana = $data['word'];
	$translations = $data['translation'];
	if (!is_array($translations)) {
		$translations = array($translations);
	}
	
	$term = new Term();
	$term->kana = $kana;
	$term->save();
	
	foreach ($translations as $translation) {
		$tr = new Translation();
		$tr->id_term = $term->id_term;
		$tr->translation = $translation;
		$tr->save();
	}
	
}


?>